
package com.crowdfunding.circle.analyze.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.analyze.entity.AnalyzeItemVO;
import com.crowdfunding.circle.analyze.entity.ProjectAnalyzeVO;
import com.crowdfunding.circle.analyze.entity.ProjectTypeVO;
import com.crowdfunding.circle.analyze.param.ProjectAnalyzeParam;
import com.crowdfunding.circle.analyze.service.ProjectAnalyzeService;
import com.crowdfunding.circle.analyze.service.ProjectTypeService;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.user.entity.UserInfoVO;
import com.crowdfunding.circle.user.service.UserInfoService;

/**
 * 拆解报告Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class ProjectAnalyzeController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ProjectAnalyzeController.class);

    @Autowired
    private ProjectAnalyzeService analyzeService;
    
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ProjectTypeService projectTypeService;

    private final static String LIST_PAGE = "/analyze/analyze_list_ajax";

    private final static String ADMIN_LIST_PAGE = "/admin/analyze_manage";

    private final static String ACCOUNT_LIST_PAGE = "/account/my_analyze";

    private final static String ACCOUNT_BUY_LIST_PAGE = "/account/buy_analyze";

    private final static String VIEW_PAGE = "/analyze/analyze_view";
    
    private final static String ADMIN_VIEW_PAGE = "/analyze/analyze_admin_view";
    
    private final static String ACCOUNT_VIEW_PAGE = "/analyze/analyze_account_view";

    private final static String UPDATE_PAGE = "/analyze/analyze_edit";

    private final static String BRFORE_INSERT_PAGE = "/analyze/analyze_before_insert";
    
    private static final String DATA_LIST_PAGE = "/analyze/analyze_data";
    
    @RequestMapping(value = "/check/analyze/beforeIntoInsert")
    public ModelAndView beforeIntoInsert() {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (seUser.getUserInfo().getIsCharge() == null || seUser.getUserInfo().getIsCharge() < 1) {
            UserInfoVO userInfoVO = userInfoService.findById(seUser.getUserId());
            resultMap.put("isCharge", userInfoVO.getIsCharge());
        } else {
            resultMap.put("isCharge", seUser.getUserInfo().getIsCharge());
        }

        List<ProjectTypeVO> projectTypeList = projectTypeService.queryAll();

        resultMap.put("dataList", projectTypeList);

        return new ModelAndView(BRFORE_INSERT_PAGE, resultMap);
    }

    @RequestMapping(value = "/check/analyze/toInsert")
    public ModelAndView intoInsert(Integer platformType, String projectId) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = analyzeService.getDataForInsert(platformType, projectId);
        if (seUser.getUserInfo().getIsCharge() == null || seUser.getUserInfo().getIsCharge() < 1) {
            UserInfoVO userInfoVO = userInfoService.findById(seUser.getUserId());
            resultMap.put("isCharge", userInfoVO.getIsCharge());
        } else {
            resultMap.put("isCharge", seUser.getUserInfo().getIsCharge());
        }

        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/analyze/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = analyzeService.getDataForUpdate(id);
        if (seUser.getUserInfo().getIsCharge() == null || seUser.getUserInfo().getIsCharge() < 2) {
            UserInfoVO userInfoVO = userInfoService.findById(seUser.getUserId());
            resultMap.put("isCharge", userInfoVO.getIsCharge());
        } else {
            resultMap.put("isCharge", seUser.getUserInfo().getIsCharge());
        }
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/analyze/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(ProjectAnalyzeVO analyze) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        String validMsg = analyze.valid();
        if (StringUtils.isNotBlank(validMsg)) {
            resultMap.put("result", false);
            resultMap.put("message", validMsg);
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer affectCount = analyzeService.update(analyze, seUser.getUserId(), request);

            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改拆解报告成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改拆解报告失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改拆解报告出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改拆解报告出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/analyze/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = analyzeService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除拆解报告成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除拆解报告失败");
            }
        } catch (Exception e) {
            logger.error("删除拆解报告出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除拆解报告出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/uncheck/analyze/list")
    public ModelAndView queryList(ProjectAnalyzeParam analyzeParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<ProjectAnalyzeVO> dataList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", analyzeParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/analyze/dataList")
    public ModelAndView queryAnalyzeDataList() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = analyzeService.queryAnalyzeDataList();
        resultMap.put("dataList", dataList);
        return new ModelAndView(DATA_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/analyze/list")
    public ModelAndView queryAdminList(ProjectAnalyzeParam analyzeParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<ProjectAnalyzeVO> dataList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", analyzeParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/account/analyze/list")
    public ModelAndView queryAccountList(ProjectAnalyzeParam analyzeParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        analyzeParam.setPublishUser(seUser.getUserId());
        List<ProjectAnalyzeVO> dataList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", analyzeParam);
        return new ModelAndView(ACCOUNT_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/account/analyze/buyList")
    public ModelAndView queryBuyAnalyzeList(ProjectAnalyzeParam analyzeParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        analyzeParam.setBuyUser(seUser.getUserId());
        List<ProjectAnalyzeVO> dataList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", analyzeParam);
        return new ModelAndView(ACCOUNT_BUY_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/analyze/view/{id}")
    public ModelAndView accountView(@PathVariable String id) {

        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        Map<String, Object> resultMap = new HashMap<String, Object>();
        ProjectAnalyzeVO analyzeVO = analyzeService.findById(id);
        resultMap.put("analyze", analyzeVO);

        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();
        
        analyzeParam.setPublishUser(analyzeVO.getPublishUser());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setProjectAnalyzeId(analyzeVO.getProjectAnalyzeId());
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);

        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);

        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);

        UserInfoVO publishUserInfo = userInfoService.findById(analyzeVO.getPublishUser());
        
        resultMap.put("publishUserInfo", publishUserInfo);

        List<AnalyzeItemVO> analyzeItemList = analyzeService.findItemById(id, seUser.getUserId());
        
        resultMap.put("analyzeItemList", analyzeItemList);
        // 发布人
        if (StringUtils.equals(analyzeVO.getPublishUser(), seUser.getUserId())) {
            resultMap.put("isPublishUser", 1);
        }

        resultMap.put("discussType", 2);
        
        resultMap.put("discussTargetId", analyzeVO.getProjectAnalyzeId());
        
        return new ModelAndView(ACCOUNT_VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/uncheck/analyze/view/{id}")
    public ModelAndView view(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ProjectAnalyzeVO analyzeVO = analyzeService.findById(id);
        resultMap.put("analyze", analyzeVO);

        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();
        
        analyzeParam.setPublishUser(analyzeVO.getPublishUser());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setProjectAnalyzeId(analyzeVO.getProjectAnalyzeId());
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);

        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);

        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);

        UserInfoVO publishUserInfo = userInfoService.findById(analyzeVO.getPublishUser());
        
        resultMap.put("publishUserInfo", publishUserInfo);

        List<AnalyzeItemVO> analyzeItemList = analyzeService.findItemById(id, null);
        
        resultMap.put("analyzeItemList", analyzeItemList);

        resultMap.put("discussType", 2);
        
        resultMap.put("discussTargetId", analyzeVO.getProjectAnalyzeId());
        
        return new ModelAndView(VIEW_PAGE, resultMap);
    }

    @RequestMapping(value = "/admin/analyze/view/{id}")
    public ModelAndView adminView(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ProjectAnalyzeVO analyzeVO = analyzeService.findById(id);
        resultMap.put("analyze", analyzeVO);

        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();
        
        analyzeParam.setPublishUser(analyzeVO.getPublishUser());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setProjectAnalyzeId(analyzeVO.getProjectAnalyzeId());
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);

        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);

        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);

        UserInfoVO publishUserInfo = userInfoService.findById(analyzeVO.getPublishUser());
        
        resultMap.put("publishUserInfo", publishUserInfo);

        List<AnalyzeItemVO> analyzeItemList = analyzeService.findItemById(id, null);
        
        resultMap.put("analyzeItemList", analyzeItemList);

        resultMap.put("discussType", 2);
        
        resultMap.put("discussTargetId", analyzeVO.getProjectAnalyzeId());
        
        return new ModelAndView(ADMIN_VIEW_PAGE, resultMap);
    }
}
